﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace DCT.AutoUpdate.Code
{
    public delegate void TimeoutControllerExecuteHandler();

    public class TimeoutController
    {
        TimeoutControllerExecuteHandler handler = null;
        private Exception executeException;

        public TimeoutController(TimeoutControllerExecuteHandler handler)
        {
            this.handler = handler;
        }

        public bool WaitExecute(TimeSpan ts)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            IAsyncResult result = this.handler.BeginInvoke(AsyncCallbackMethod, null);
            if (result.AsyncWaitHandle.WaitOne(ts))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void AsyncCallbackMethod(IAsyncResult r)
        {
            try
            {
                this.handler.EndInvoke(r);
            }
            catch (Exception ex)
            {
                this.executeException = ex;
            }
        }
    }
}
